import { login, logout, getUserInfo,smsLogin,resetPassword,smsRegister } from '@/api/login';
const persistedUserInfo = JSON.parse(localStorage.getItem('userInfo')) || null;
const state = {
  token: null, // app token
  userName: null,
  userInfo: persistedUserInfo,
  menu: [],
  permission: [],
  cdnUrl: process.env.VUE_APP_CDN_URL || 'https://bbt.dev-hb-bkt.ufozx.com', // 使用环境变量或默认值
};



const mutations = {
  setToken: (state, token) => {
    window.localStorage.setItem('Authorization', token);
    state.token = token;
  },
  setAccountName: (state, userName) => {
    window.localStorage.setItem('userName', userName);
    state.userName = userName;
    state.userInfo = null;
    localStorage.removeItem('userInfo');
  },
  setUserInfo: (state, userInfo) => {
    
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
    state.userInfo = userInfo;
    console.log('userInfo',state.userInfo);
  },
  setMenu: (state, menuInfo) => {
    state.menu = menuInfo;
    window.localStorage.setItem('menu', JSON.stringify(menuInfo));
    window.localStorage.setItem('menu', JSON.stringify(state.menu));
  },
  setPermission: (state, permission) => {
    state.permission = permission;
    window.localStorage.setItem('permission', JSON.stringify(permission));
  },
};

const actions = {
  // 登录
  Login({ commit }, params) {
    return new Promise((resolve, reject) => {
      login(params)
        .then((res) => {
          // const { accountName, token } = res.data;
          // commit('setToken', token);
          // commit('setAccountName', accountName);
          if (res.error === 0) {
            resolve(res);
          }
          
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  SmsLogin({ commit }, params) {
    return new Promise((resolve, reject) => {
      smsLogin(params)
        .then((res) => {
          // const { accountName, token } = res.data;
          // commit('setToken', token);
          // commit('setAccountName', accountName);
          if (res.error === 0) {
            resolve(res);
          }
          
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  //修改密码
  ResetPassword({ commit }, params) {
    return new Promise((resolve, reject) => {
      resetPassword(params)
        .then((res) => {
          // const { accountName, token } = res.data;
          // commit('setToken', token);
          // commit('setAccountName', accountName);
          if (res.error === 0) {
            resolve(res);
          }
          
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  SmsRegister({ commit }, params) {
    return new Promise((resolve, reject) => {
      smsRegister(params)
        .then((res) => {
          // const { accountName, token } = res.data;
          // commit('setToken', token);
          // commit('setAccountName', accountName);
          if (res.error === 0) {
            resolve(res);
          }
          
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 登出
  Logout({ commit, state }) {
    return new Promise((resolve) => {
      logout()
        .then(() => {
          resolve(true);
        })
        .catch(() => {
          resolve(true);
        })
        .finally(() => {
          commit('setToken', null);
          commit('setAccountName', null);
          resolve(true);
        });
    });
  },
  // 获取用户信息
  FetchUserInfo({ commit }, token) {
    return new Promise((resolve, reject) => {
      getUserInfo(token)
        .then((res) => {
          console.log(res);
          
          if (res.error === 0) {
            commit('setUserInfo', res.data);
            window.localStorage.setItem('userInfo', JSON.stringify(res.data));
            // commit('setPermission', extractPermissions(res.data));
            resolve('/mission-hall');
            console.log('mission-hall',res);
            
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

const getters = {
  getUserInfo: (state) => state.userInfo,
  getCdnUrl: (state) => state.cdnUrl,
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};

function extractPermissions(data) {
  const permissions = [];
  data.forEach((item) => {
    if (item.permission) {
      permissions.push(item.permission.split(','));
    }
    if (item.children && item.children.length) {
      permissions.push(item.children.map((it) => it.permission.split(',')));
    }
  });
  return permissions.flat(Infinity);
}

// function getCurrentRouters(name) {
//   const routers = RouterPermission.find((it) => it.name === name);
//   return routers ? routers.path : [];
// }
